package org.jeecg.modules.wlhy.hydriver.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.paycenter.channel.bankdocking.service.NhBankService;
import org.jeecg.modules.paycenter.service.WalletService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriverAccountBook;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverAccountBookService;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: hy_driver_account_book
 * @Author: jeecg-boot
 * @Date:   2021-01-16
 * @Version: V1.0
 */
@Api(tags="hy_driver_account_book")
@RestController
@RequestMapping("/driver/hyDriverAccountBook")
//@RequiresRoles(value={"admin", "customer", "driver"},logical = Logical.OR)
@Slf4j
public class HyDriverAccountBookController extends JeecgController<HyDriverAccountBook, IHyDriverAccountBookService> {
	@Autowired
	private IHyDriverAccountBookService hyDriverAccountBookService;

	@Autowired
	private IHyDriverService hyDriverService;

	@Autowired
	private NhBankService nhBankService;

	@Autowired
	private UserUtil userUtil;

	@Autowired
	private WalletService walletService;

	@Autowired
	private IHyDriverBankService hyDriverBankService;

	@Value("${pay-config.trade.begin:8}")
	private String TRADE_BEGIN;

	@Value("${pay-config.trade.end:19}")
	private String TRADE_END;

	@Value("${pay-config.cash-out.active:1}")
	private String CASHOUT_ACTIVE;

	@Value("${pay-config.cash-out.begin:8}")
	private String CASHOUT_BEGIN;

	@Value("${pay-config.cash-out.end:19}")
	private String CASHOUT_END;

	@Value("${pay-config.sms-active:0}")
	private String CASH_OUT_SMS_ACTIVE;

	@Value("${pay-config.acc-sms-active:0}")
	private String ACC_SMS_ACTIVE;

//	@Autowired
//	private BankUtils bankUtils;


	@ApiOperation(value="获取司机多级账簿信息", notes="获取司机多级账簿信息")
	@GetMapping(value = "/getAccountBookInfo")
	@RequiresPermissions("driver:getAccountBook")
	public Result<?> getAccountBookInfo(String driverId) {
		if(StringUtils.isEmpty(driverId)){
			return Result.error("司机信息不存在");
		}
		HyDriver driver = hyDriverService.getById(driverId);
		if(driver == null){
			return Result.error("司机信息不存在");
		}
		//是否开通过
		HyDriverAccountBook accountBook = hyDriverAccountBookService.getAccountBookByDriverId(driver.getId());
		if(accountBook == null){
			return Result.OK(null);
		}
		accountBook.setPayPwd("");
		nhBankService.getDriverAccBookInfo(accountBook);
		return Result.OK(accountBook);
	}


	@AutoLog(value = "货主-开通司机钱包")
	@ApiOperation(value="货主-开通司机钱包", notes="货主-开通司机钱包")
	@PostMapping(value = "/addAccountBook")
	@RequiresPermissions("driver:addAccountBook")
	public Result<?> addAccountBook(@RequestBody Map<String,String> params) {
		if (DateUtil.hour(new Date(), true)>Integer.parseInt(TRADE_END) || DateUtil.hour(new Date(), true) < Integer.parseInt(TRADE_BEGIN)){
			return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		}

		HyConfig config = HyConfigUtils.getConfig();
		if(!config.getNhbankIzUse()){
			return Result.error("未开通服务！");
		}

		String driverId = params.get("driverId");
		if(StringUtils.isEmpty(driverId)){
			return Result.error("司机信息不存在");
		}
		//是否开通过
		HyDriverAccountBook accountBook = hyDriverAccountBookService.getAccountBookByDriverId(driverId);
		if(accountBook != null){
			return Result.error("不能重复开通");
		}
		HyDriver driver = hyDriverService.getById(driverId);
		if(driver == null){
			return Result.error("司机信息不存在");
		}
		HyDriverAccountBook hyDriverAccountBook = new HyDriverAccountBook();
		hyDriverAccountBook.setPayPwd("123456");
		hyDriverAccountBookService.addAccountBook(hyDriverAccountBook,driver);
		return Result.OK("添加成功！");
	}

	@AutoLog(value = "货主-批量开通司机钱包")
	@ApiOperation(value="货主-批量开通司机钱包", notes="货主-批量开通司机钱包")
	@PostMapping(value = "/batchAddAccountBook")
	@RequiresPermissions("driver:addAccountBook")
	public Result<?> batchAddAccountBook(@RequestParam(name="ids",required=true) String ids) {
		if (DateUtil.hour(new Date(), true)>Integer.parseInt(TRADE_END) || DateUtil.hour(new Date(), true) < Integer.parseInt(TRADE_BEGIN)){
			return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		}

		HyConfig config = HyConfigUtils.getConfig();
		if(!config.getNhbankIzUse()){
			return Result.error("未开通服务！");
		}
		List<String> driverIds = Arrays.asList(ids.split(","));
		if(driverIds.size()==0){
			return Result.error("请选择司机！");
		}
		List<HyDriver> hyDrivers = hyDriverService.listByIds(driverIds);
		if(hyDrivers.size() > 0) {
			List<String> driverNames = new ArrayList<>();
			for (HyDriver driver : hyDrivers) {
				//是否开通过
				HyDriverAccountBook accountBook = hyDriverAccountBookService.getAccountBookByDriverId(driver.getId());
				if (accountBook != null) {
					continue;
				}
				HyDriverAccountBook hyDriverAccountBook = new HyDriverAccountBook();
				hyDriverAccountBook.setPayPwd("123456");
				try {
					hyDriverAccountBookService.addAccountBook(hyDriverAccountBook, driver);
				} catch (Exception e) {
					driverNames.add(driver.getDriverName());
				}
			}
			if(driverNames.size() > 0){
				return Result.error(String.join("," ,driverNames) + "未开通成功");
			}
		}
		return Result.OK("开通成功！");
	}

	@AutoLog(value = "司机提现")
	@ApiOperation(value="司机提现", notes="司机提现")
	@PostMapping(value = "/tx")
	public Result<?> tx(@RequestBody JSONObject jsonObject) {
		if ("1".equalsIgnoreCase(CASHOUT_ACTIVE)
				&&( DateUtil.hour(new Date(), true)>Integer.parseInt(CASHOUT_END) || DateUtil.hour(new Date(), true) <Integer.parseInt(CASHOUT_BEGIN))){
			return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		}

		HyConfig config = HyConfigUtils.getConfig();
		if (!config.getNhbankIzUse()) {
			return Result.error("未开通服务！");
		}
		String pwd = jsonObject.getString("pwd");
		String driverBankId = jsonObject.getString("driverBankId");
		String driverId = jsonObject.getString("driverId");
		String samt = jsonObject.getString("amt");

		if (StringUtils.isEmpty(pwd)) {
			return Result.error("支付密码不能为空！");
		}
		if (StringUtils.isEmpty(driverBankId)) {
			return Result.error("请选择银行卡！");
		}
		if (StringUtils.isEmpty(samt)) {
			return Result.error("提现金额不能为空！");
		}
		if (StringUtils.isEmpty(driverId)) {
			return Result.error("司机id不能为空！");
		}
		BigDecimal amt = null;
		try {
			amt = new BigDecimal(samt);
		} catch (Exception e) {
			return Result.error("提现金额格式错误！");
		}
		// 0 > amt
		if (BigDecimal.ZERO.compareTo(amt) == 1) {
			return Result.error("提现金额错误！");
		}
		if (!userUtil.isSys()) {
			return Result.error("无权限操作！");
		}
		if (!walletService.checkPwd(pwd)) {
			return Result.error("支付密码错误");
		}
		HyDriver driver = hyDriverService.getById(driverId);
		if (driver == null) {
			return Result.error("司机信息不存在!");
		}
		return nhBankService.tx(driver, driverBankId, amt);
	}

//	/**
//	 * 分页列表查询
//	 *
//	 * @param hyDriverAccountBook
//	 * @param pageNo
//	 * @param pageSize
//	 * @param req
//	 * @return
//	 */
//	@AutoLog(value = "hy_driver_account_book-分页列表查询")
//	@ApiOperation(value="hy_driver_account_book-分页列表查询", notes="hy_driver_account_book-分页列表查询")
//	@GetMapping(value = "/list")
//	public Result<?> queryPageList(HyDriverAccountBook hyDriverAccountBook,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//		QueryWrapper<HyDriverAccountBook> queryWrapper = QueryGenerator.initQueryWrapper(hyDriverAccountBook, req.getParameterMap());
//		Page<HyDriverAccountBook> page = new Page<HyDriverAccountBook>(pageNo, pageSize);
//		IPage<HyDriverAccountBook> pageList = hyDriverAccountBookService.page(page, queryWrapper);
//		return Result.OK(pageList);
//	}
//
//	/**
//	 *   添加
//	 *
//	 * @param hyDriverAccountBook
//	 * @return
//	 */
//	@AutoLog(value = "hy_driver_account_book-添加")
//	@ApiOperation(value="hy_driver_account_book-添加", notes="hy_driver_account_book-添加")
//	@PostMapping(value = "/add")
//	public Result<?> add(@RequestBody HyDriverAccountBook hyDriverAccountBook) {
//		hyDriverAccountBookService.save(hyDriverAccountBook);
//		return Result.OK("添加成功！");
//	}
//
//	/**
//	 *  编辑
//	 *
//	 * @param hyDriverAccountBook
//	 * @return
//	 */
//	@AutoLog(value = "hy_driver_account_book-编辑")
//	@ApiOperation(value="hy_driver_account_book-编辑", notes="hy_driver_account_book-编辑")
//	@PutMapping(value = "/edit")
//	public Result<?> edit(@RequestBody HyDriverAccountBook hyDriverAccountBook) {
//		hyDriverAccountBookService.updateById(hyDriverAccountBook);
//		return Result.OK("编辑成功!");
//	}
//
//	/**
//	 *   通过id删除
//	 *
//	 * @param id
//	 * @return
//	 */
//	@AutoLog(value = "hy_driver_account_book-通过id删除")
//	@ApiOperation(value="hy_driver_account_book-通过id删除", notes="hy_driver_account_book-通过id删除")
//	@DeleteMapping(value = "/delete")
//	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
//		hyDriverAccountBookService.removeById(id);
//		return Result.OK("删除成功!");
//	}
//
//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "hy_driver_account_book-批量删除")
//	@ApiOperation(value="hy_driver_account_book-批量删除", notes="hy_driver_account_book-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyDriverAccountBookService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}
//
//	/**
//	 * 通过id查询
//	 *
//	 * @param id
//	 * @return
//	 */
//	@AutoLog(value = "hy_driver_account_book-通过id查询")
//	@ApiOperation(value="hy_driver_account_book-通过id查询", notes="hy_driver_account_book-通过id查询")
//	@GetMapping(value = "/queryById")
//	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
//		HyDriverAccountBook hyDriverAccountBook = hyDriverAccountBookService.getById(id);
//		if(hyDriverAccountBook==null) {
//			return Result.error("未找到对应数据");
//		}
//		return Result.OK(hyDriverAccountBook);
//	}
//
//    /**
//    * 导出excel
//    *
//    * @param request
//    * @param hyDriverAccountBook
//    */
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(HttpServletRequest request, HyDriverAccountBook hyDriverAccountBook) {
//        return super.exportXls(request, hyDriverAccountBook, HyDriverAccountBook.class, "hy_driver_account_book");
//    }
//
//    /**
//      * 通过excel导入数据
//    *
//    * @param request
//    * @param response
//    * @return
//    */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, HyDriverAccountBook.class);
//    }

}
